package com.lll.find;

import com.lll.constant.Configuration;
import com.lll.student.StudentImpl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class StudentFind {
    /**
     * 得到没有交文件的学生
     * @return
     */
    public List<String> notExistStudent() throws IOException {
        //得到学生列表
        List<String> studentListAll = StudentImpl.getStudentList();
        //得到文件夹的名字
        String folderName = this.getFolderName();
        //得到所有文件夹中的文件名
        String fileStr =
                getFolderInAllFileName("C:\\Users\\super\\Desktop\\"+folderName);
        List<String> notExistList = studentListAll.stream()
                .filter(s -> !fileStr.contains(s))
                .collect(Collectors.toList());
        return notExistList;
    }

    private String getFolderInAllFileName(String absolutePath) throws IOException {
        if(absolutePath == null || absolutePath.isEmpty()){
            //如果是null或者是空串，就返回空
            return null;
        }
        File file = new File(absolutePath);
        boolean directory = file.isDirectory();
        //还要判断存不存在
        if(!file.exists()){
            throw new RuntimeException("没有这个文件夹");
        }
        if(!directory){
            throw new RuntimeException("不是文件夹，必须是文件夹");
        }
        //考虑递归，之考虑一层的文件
        StringBuilder sb = new StringBuilder();
        List<Path> list = Files.walk(Paths.get(absolutePath))
                .filter(Files::isRegularFile)
                .collect(Collectors.toList());
        for (Path path : list) {
            sb.append(path.getFileName().toString());
        }
        return sb.toString();
    }

    /**
     * 得到文件夹的名字
     * @return
     */
    private String getFolderName(){
        InputStream stream =
                this.getClass().getClassLoader().getResourceAsStream(Configuration.CONFIGURATION_FILE_NAME);
        if(stream == null){
            throw new RuntimeException("找不到configuration.properties，请在resources目录中配置");
        }
        Properties properties = new Properties();
        try {
            properties.load(new InputStreamReader(stream,StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byte[] bytes = properties.getProperty(Configuration.FOLDER_NAME).getBytes(StandardCharsets.UTF_8);
        return new String(bytes);
    }
}
